<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\LoginRequest;
use App\Model\User\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class Banding extends Controller
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $input = $request->all();
        $input['weixin_id'] = $input['weixin_id'] ?? '';
        $user_meal = User::where('weixin_id', $input['weixin_id'])->with('meal_supplement_balance')->first();
        if (empty($user_meal)) {
            $user_meal['weixin_id'] = $input['weixin_id'];
        }
        return view('binding.index', $user_meal);
    }

    public function store(LoginRequest $request)
    {
        $validator = $request->validated();
        $input = $request->all();
        if (Auth::attempt(['username' => request('username'), 'password' => request('password'), 'is_active' => 1])) {
            $user = Auth::user();
            if (empty($user->weixin_id)) {
                $user->weixin_id = $input['weixin_id'];
                $user->save();
            } else {
                return redirect('binding?weixin_id=' . $input['weixin_id'])->withErrors(['该用户已被其他微信号绑定过，如有问题请联系管理员！']);
            }
        }
        return redirect('binding?weixin_id=' . $input['weixin_id']);
//        return redirect('binding');
    }
}
